package com.example.springbootdemo.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @Author: ShengXiaJia
 * @Date: 2019/12/20 10:14
 * @Description: OSS存储工具类
 */
public class OSSUtil {

    // 指定存储空间
    private static String bucketName = "";
    // Endpoint以杭州为例，其它Region请按实际情况填写
    private static String endpoint = "";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号
    private static String accessKeyId = "";
    private static String accessKeySecret = "";
    // 创建OSSClient实例
    private static OSSClient ossClient = null;

    /**
     * 创建存储空间
     */
    public static void newBucket(String bucketName) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 创建存储空间
        ossClient.createBucket(bucketName);
        // 关闭OSSClient
        ossClient.shutdown();
    }

    /**8
     * 删除存储空间
     */
    public static void delBucket(String bucketName) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 删除存储空间
        ossClient.deleteBucket(bucketName);
        // 关闭OSSClient
        ossClient.shutdown();
    }

    /**
     * 列举存储空间
     */
    public static void listAllBucket() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 列举存储空间
        List<Bucket> buckets = ossClient.listBuckets();
        System.out.println("--------- 存储空间 --------");
        for (Bucket bucket : buckets) {
            System.out.println(bucket.getName());
        }
        System.out.println("--------- 存储空间 --------");
        // 关闭OSSClient
        ossClient.shutdown();
    }

    /**
     * 列举指定前缀的存储空间
     */
    public static void listPrefixBucket(String prefix) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
        // 列举指定前缀的存储空间
        listBucketsRequest.setPrefix(prefix);
        BucketList bucketList = ossClient.listBuckets(listBucketsRequest);
        for (Bucket bucket : bucketList.getBucketList()) {
            System.out.println(" - " + bucket.getName());
        }
        ossClient.shutdown();
    }

    /**
     * 列举存储空间下的文件
     */
    public static List<OSSObjectSummary> ListFile(String keyPrefix) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 设置最大个数。
        final int maxKeys = 1000;
        ObjectListing objectListing;
        if (keyPrefix == null || "".equals(keyPrefix)) {
            objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
        } else {
            objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys).withPrefix(keyPrefix));
        }
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();

        // objectListing.getObjectSummaries获取所有文件的描述信息
        System.out.println("--------- 文件 --------");
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
        }
        System.out.println("--------- 文件 --------");
        // 关闭OSSClient
        ossClient.shutdown();
        return sums;
    }

    /**
     * 上传文件,并返回文件访问url
     */
    public static String uploadFileInput(String objectName, InputStream fileContent) throws IOException {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）
        try {
            // 上传文件
            ossClient.putObject(bucketName, objectName, fileContent);
            // 关闭OSSClient
            ossClient.shutdown();
            // 关闭io流
            fileContent.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭OSSClient
        ossClient.shutdown();
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        return url.toString();
    }

    /**
     * 上传文件
     */
    public static String uploadFileByte(String objectName, byte[] b) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）
        ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(b));
        // 关闭OSSClient
        ossClient.shutdown();
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        return url.toString();
    }

    /**
     * 下载文件
     */
    public static String downloadFile(String objectName) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容
            InputStream content = ossObject.getObjectContent();
            StringBuffer sb = new StringBuffer();
            if (content != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                while (true) {
                    String line = null;
                    line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    sb.append(line);
                }
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作
                content.close();
            }
            // 关闭OSSClient。
            ossClient.shutdown();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除单个文件
     */
    public static void delFile(String objectName) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 删除文件
        ossClient.deleteObject(bucketName, objectName);
        // 关闭OSSClient
        ossClient.shutdown();
    }

    /**
     * 删除多个文件
     */
    public static void delFileList(List<String> keys) {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 删除文件
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        // 关闭OSSClient
        ossClient.shutdown();
    }

    /**
     * 获得文件路径
     */
    public static String getFileUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            // 生成URL
            URL url = ossClient.generatePresignedUrl(bucketName, fileUrl, expiration);
            if (url != null) {
                return url.toString();
            }
        }
        return null;
    }

}
